#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.db import connection

from web.dao.base_dao import BaseDao
from web.manager.log_manager import LogManager
from web.models.quant2_account import Quant2Account

Logger = LogManager.get_logger(__name__)

class Quant2AccountDao(BaseDao):
    """
    Quant2Account的dao类
    """

    model_class = Quant2Account

    def find_all(self):
        """
        查询所有记录
        """

        return self.find_list(dict(), dict(), dict())

    def find_by_account_name(self, account_name:str) -> Quant2Account:
        """
        根据账户名称查询记录
        """

        filter_dict = {'account_name': account_name}
        return self.find_list(filter_dict(), dict(), list())

    def update_after_close_position(self, sell_or_buy_commodity_future_number: int, commodity_future_assets: float, current_close_commodity_future_assets: float, account_name: str):
        """
        平仓之后更新quant2_account
        """

        with connection.cursor() as cursor:
            sql: str = "update quant2_account t " \
			"set t.hold_commodity_future_number = {}, " \
             "t.commodity_future_assets = round({}, 4), " \
             "t.capital_assets = round(t.capital_assets + {}, 4), " \
            "t.total_assets = round(t.capital_assets + {} + {}, 4), " \
			"t.total_open_commission = (select COALESCE(sum(t1.open_commission), 0) from quant2_c_f_transact_record t1 where t1.account_name = '{}'), " \
			"t.total_close_commission = (select COALESCE(sum(t1.close_commission), 0) from quant2_c_f_transact_record t1 where t1.account_name = '{}') " \
			"where t.account_name = '{}'".format(sell_or_buy_commodity_future_number,
                                                 commodity_future_assets,
                                                 current_close_commodity_future_assets,
                                                 commodity_future_assets, current_close_commodity_future_assets,
                                                 account_name,
                                                 account_name,
                                                 account_name)

            cursor.execute(sql)

    def update_after_open_position(self, sell_or_buy_commodity_future_number: int, commodity_future_assets: float,
                                   current_open_position_commission: float, current_open_commodity_future_assets: float, account_name: str):
        """
        开仓之后更新quant2_account。
        capital_assets = capital_assets - 新开仓的期货成本 - 新开仓的期货费用
        total_assets = 全部期货资产（包括已经持仓的和新开仓的） + capital_assets - 新开仓的期货成本 - 新开仓的期货费用
        """

        with connection.cursor() as cursor:
            sql: str = "update quant2_account " \
			"set hold_commodity_future_number = {}, " \
            "commodity_future_assets = round({}, 4), " \
            "total_assets = round({} + capital_assets - {} - {}, 4), " \
            "capital_assets = round(capital_assets - {} - {}, 4), " \
            "total_open_commission = round(total_open_commission + {}, 4) " \
            "where account_name = '{}'".format(sell_or_buy_commodity_future_number,
                                               commodity_future_assets,
                                               commodity_future_assets, current_open_commodity_future_assets, current_open_position_commission,
                                               current_open_commodity_future_assets, current_open_position_commission,
                                               current_open_position_commission,
                                               account_name)
            cursor.execute(sql)

    def tuple_list_to_quant_account_list(self, tuple_list: list) -> list[Quant2Account]:
        """
        将tuple列表转换为Quant2Account列表
        """

        if tuple_list is not None and len(tuple_list) > 0:
            quant2_account_list: list[Quant2Account] = list()
            for _tuple in tuple_list:
                quant2_account: Quant2Account = Quant2Account()
                quant2_account.id = _tuple[0]
                quant2_account.date_ = _tuple[1]
                quant2_account.account_name = _tuple[2]
                quant2_account.hold_commodity_future_number = _tuple[3]
                quant2_account.commodity_future_assets = _tuple[4]
                quant2_account.capital_assets = _tuple[5]
                quant2_account.total_assets = _tuple[6]
                quant2_account.total_open_commission = _tuple[7]
                quant2_account.total_close_commission = _tuple[8]
                quant2_account_list.append(quant2_account)
            return quant2_account_list
        else:
            return None